<template>
  <div class="skill-tree-bg">
    <div class="skill-tree-root">
      <SkillTreeNode
        v-for="(node, key) in treeStats"
        :key="key"
        :node="node"
        :level="1"
        :getName="getNameByPath"
      />
    </div>
  </div>
</template>

<script setup>
import SkillTreeNode from './SkillTreeNode.vue'
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import { categories } from '@/utils/skillUtils'
import { getCurrentConfig } from '@/config/environment'

const route = useRoute()
const uid = route.query.uid

const today = new Date()
const lastYear = new Date()
lastYear.setFullYear(today.getFullYear() - 1)

const formatDate = (date) => date.toISOString().slice(0, 10)
const startDate = ref(formatDate(lastYear))
const endDate = ref(formatDate(today))

const loading = ref(false)
const error = ref('')
const totalBadges = ref(0)
const treeStats = ref({})

function getNameByPath(path) {
  if (!path) return ''
  if (path.length === 2) {
    const cat = categories.find(c => c.code === path)
    return cat ? cat.name : path
  }
  if (path.length === 4) {
    for (const cat of categories) {
      const sub = cat.subcategories.find(s => s.code === path)
      if (sub) return sub.name
    }
    return path
  }
  if (path.length === 6) {
    for (const cat of categories) {
      for (const sub of cat.subcategories) {
        const dir = sub.directions.find(d => d.code === path)
        if (dir) return dir.name
      }
    }
    return path
  }
  return path
}

async function fetchTree() {
  loading.value = true
  error.value = ''
  try {
    const token = localStorage.getItem('accessToken')
    const config = getCurrentConfig()
    const res = await axios.get(`${config.apiBaseUrl}/badge/skill-tree`, {
      params: {
        uid,
        start: startDate.value + 'T00:00:00',
        end: endDate.value + 'T23:59:59'
      },
      headers: { 'Access-Token': `Bearer ${token}` }
    })
    totalBadges.value = res.data.totalBadges
    treeStats.value = res.data.treeStats
  } catch (e) {
    error.value = e?.response?.data?.error || e.message || '加载失败'
  } finally {
    loading.value = false
  }
}

onMounted(fetchTree)
</script>

<style scoped>
.skill-tree-bg {
  background: #0a1833;
  min-height: 100vh;
  position: relative;
  overflow-x: auto;
  /* 可加网格背景 */
}
.skill-tree-root {
  position: relative;
  padding: 60px 0;
  display: flex;
  justify-content: flex-start;
  width: max-content;      /* 关键：内容宽度自适应所有节点 */
  overflow-x: visible;     /* 由外层控制滚动 */
  overflow-y: visible;
  white-space: nowrap;
}
.tree-children.level-1 { gap: 600px; }
.tree-children.level-2 { gap: 240px; }
.tree-children.level-3, .tree-children.level-4, .tree-children.level-5 { gap: 60px; }
.skill-tree-root::-webkit-scrollbar {
  height: 8px;
  background: #1a2a44;
}
.skill-tree-root::-webkit-scrollbar-thumb {
  background: #36a;
  border-radius: 4px;
}
</style>